package com.sense.kukoo.biz_explore.vm

import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.sense.kukoo.biz_explore.model.MusicCollectionModel
import com.sense.kukoo.common.mvvm.model.BaseMvvmModel
import com.sense.kukoo.common.mvvm.vm.BaseViewModel
import com.sense.kukoo.common.repo.Repo
import com.sense.kukoo.common.repo.bean.*
import com.sense.kukoo.lib_logger.LoggerManager

class MusicCollectionViewModel :BaseViewModel() {

    private val TAG: String = javaClass.simpleName
    private var mIndex = 1
    private val mPageSize = 10
    private lateinit var mExploreContentBean: ExploreContentBean

    val mMusicCollection: MutableLiveData<ArrayList<MusicCollectionBean>> = MutableLiveData()
    val enableLoadMore: MutableLiveData<Boolean> = MutableLiveData(true)

    override fun createModel(): BaseMvvmModel? = null

    override fun initData() {}

    fun initData(bean: ExploreContentBean){
        mExploreContentBean = bean
    }

    fun refreshData(){
        mIndex = 1
        enableLoadMore.postValue(true)
        loadData()
    }

    fun loadMoreData(){
        loadData()
    }

    private fun loadData(){
        request {
            val result = Repo.http.getMoreData(mIndex, mPageSize, mExploreContentBean.code!!)
            if (result.success) {
                val data: QueryPageBean<BookBean> = result.data!!
                val formate = formateData(data)
                //
                LoggerManager.e(TAG,"getMoreData -> success")
                mIndex++
                if(data.records.size < mPageSize){
                    LoggerManager.e(TAG,"ACTION_NO_MORE_DATA data.records.size=${data.records.size}")
                    enableLoadMore.postValue(false)
                }
                val value = mMusicCollection.value ?: arrayListOf()
                value.addAll(formate)
                mMusicCollection.postValue(value)
            } else {
                Log.e(TAG, "result0=" + result.msg)
                result.msg.let { sendHintMessage(it) }
            }
        }
    }

    private fun formateData(data: QueryPageBean<BookBean>):List<MusicCollectionBean>{
        val list = arrayListOf<MusicCollectionBean>()
        data.records.forEachIndexed { index, bookBean ->
            list.add(MusicCollectionBean(book = bookBean))
        }
        return list
    }

}